<template>
	<!-- 入库验收组件 -->
	<view class="main">
		<!-- 商品信息区域 -->
		<view class="info-group name">
			<view class="info-label">品名：</view>
			<view class="name-container">
				<view v-for="(name, index) in product.goodName || []" :key="name.id || index" class="name_item">
					{{ name.goodName || '未知名称' }}
				</view>
			</view>
		
		</view>
		<view class="photo" @click="handlepicpopup">
			<view class=""><uni-icons type="image" size="30" color="#ccc"></uni-icons>
			<text>参考图片</text></view>
		
		</view>

		<view class="info-group spec">
			<text class="info-label">规格：</text>
			<text class="spec-value">{{ acceptItem.spec?.specStr || '未知规格' }}</text>
		</view>
		<!-- 商品图片点击弹窗外区域 -->

		<uni-popup ref="picpopup" type="top">
			<view class="productPic-container" v-if="product.photo && product.photo.length > 0">
				<view class="productPic-placeholder" @click="showPictures = true">
					<uni-icons type="image" size="40" color="#666"></uni-icons>
					<text class="productPic-text">点击查看商品图片 ({{ product.photo.length }})</text>
				</view>

				<!-- 图片轮播（点击显示） -->
				<view class="productPic-wrapper" v-if="showPictures">
					<view class="productPic-overlay" @click="showPictures = false"></view>
					<view class="productPic-modal">
						<view class="productPic-close" @click="showPictures = false">
							<uni-icons type="close" size="30" color="#fff"></uni-icons>
						</view>
						<swiper :indicator-dots="true" :autoplay="false" :interval="3000" :duration="1000" :circular="product.photo.length > 1">
							<swiper-item v-for="(pic, index) in product.photo" :key="index">
								<view class="swiper-item">
									<image :src="pic" mode="widthFix" @error="onImgError(index)" class="product-img"></image>
								</view>
							</swiper-item>
						</swiper>
					</view>
				</view>
			</view>
			<!-- 无图片时显示占位区域 -->
			<view class="no-pic" v-else>
				<uni-icons type="image" size="60" color="#ccc"></uni-icons>
				<text class="no-pic-text">暂无商品图片</text>
			</view>
		</uni-popup>
		<!-- 数量信息 -->
		<view class="info-group">
			<view class="quantity-item">
				<text class="info-label">申请数量:</text>
				<text>{{ acceptItem.quantity }}{{ acceptItem.unit?.unitName || '' }}</text>
				<text class="quantity-note">(注：{{ beforeUnitRead() }})</text>
			</view>
			<view class="check-status">
				<text class="info-label">验收情况：</text>
				<text>{{ checkReadMe() || '未填写' }}</text>
			</view>
		</view>

		<!-- 验收指令选择 -->
		<view class="batch_order">
			<view class="">验收要求：</view>
			<text>{{ acceptItem.batchOrder ? acceptItem.batchOrder.map((item) => item.batchName).join(',') : '' }}</text>
		</view>

		<scroll-view scroll-y="true" class="scroll" :scroll-with-animation="true">
			<view class="scroll-content">
				<!-- 验收明细区域 -->
				<view class="order_area">
					<view class="order_item">
						<view class="" v-for="(unit, index) in selectUnitList" :key="index">
							<view class="quantity_0" @click="handleCurrentIndex(index)">
								<view class="add no">{{ index + 1 }}</view>

								<picker mode="selector" :range="acceptType" :value="acceptTypeIndex" @change="selectAcceptType(index, $event)" range-key="title">
									<view class="acceptType" :class="{ acceptType_err: unit.acceptType.type !== 'normal' }">
										<text>{{ unit.acceptType.title }}</text>
										<uni-icons type="down"></uni-icons>
									</view>
								</picker>
								<view v-if="acceptItem.batchOrder.findIndex(i=>i.id==='1')!==-1" class="input batch"><input type="text" v-model="unit.batchNo" placeholder="批次号" /></view>
								<view  v-if="acceptItem.batchOrder.findIndex(i=>i.id==='2')!==-1" class="input mode_date">
							      <picker mode="date" :value="productionDate" @change="seleData(index,$event)" >
							      	<view>
										<input type="text" v-model="unit.productionDate" placeholder="生产日期" />
								   </view>
							      </picker>
							
								
								
								</view>

								<input class="input quantity" type="number" v-model="unit.quantity" placeholder="数量" />

								<picker mode="selector" :range="product.unit" :value="selecunitValue" range-key="unitName" @change="selectUnit(index, $event)">
									<view class="unitarea">
										<view class=""><input type="text" v-model="unit.unit.unitName" readonly /></view>
										<view class=""><uni-icons type="down"></uni-icons></view>
									</view>
								</picker>
								<view class="" v-if="acceptItem.batchOrder.findIndex(i=>i.id==='3')!==-1">
									<uni-icons type="scan" size="30"></uni-icons>
								<text>{{ 
								  !productionCode || productionCode.length === 0 
								    ? '请输入序列号' 
								    : `${productionCode.length}` 
								}}</text>
								</view>
								<view class="input cumtom" v-if="acceptItem.batchOrder.findIndex(i=>i.id==='4')!==-1">
									<uni-icons type="compose" size="30"></uni-icons>
									<input type="text"></input>
								</view>
								<view class="del action-btn" @click.stop="delUnit(index)"><uni-icons type="trash" size="20" color="red"></uni-icons></view>
							</view>
							<view v-if="index === selectUnitList.length - 1" class="add" @click.stop="addUnit(index)">+添加</view>
						</view>

						<!-- 底部占位元素，确保最后一行有间距 -->
						<view class="bottom-spacing"></view>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 底部操作按钮 -->
		<view class="btn-group">
			<view class="cancel-btn" @click="close">取消</view>
			<view class="confirm-btn" @click="handleConfirm">确认验收</view>
		</view>
	</view>
</template>

<script>
const CloudDB = uniCloud.importObject('getDb');
import unitRead from '../../untils/unitRead';
import { acceptType } from '../../untils/acceptType';
import { store } from '../../uni_modules/uni-id-pages/common/store.js';
import getImgUrl from '../../untils/getImgUrl';

export default {
	name: 'checkAccept',
	props: {
		acceptItem: {
			type: Object,
			required: true,
			default: () => ({}) // 避免空值报错
		}
	},

	data() {
		return {
			photos: [],
			acceptType,
			acceptTypeIndex: 0,
			currentIndex: -1,
			product: {},
			quantities: [], // 存储各单位对应的数量
			unitNow: null,
			orderVal: '',
			selectUnitList: [],
			selecunitValue: 0,
			entryQuantiy: 0, // 验收输入的数量
			checkEntry: { unit: null, quantity: 0, acceptType: {} },
			showPictures: false, // 控制图片显示状态
			acceptanceStatus: null,
			productionDate:'',
			productionCode:'',
			batchNo:'',
		};
	},

	computed: {
		// 计算总数量（转换为基准单位）
		total() {
			return this.selectUnitList.reduce((sum, item) => {
				const relationship = Number(item.unit?.relationship) || 0;
				const quantity = Number(item.quantity) || 0;
				return sum + relationship * quantity;
			}, 0);
		},

		// 按验收类型统计
		total_fale() {
			return this.selectUnitList.reduce((acc, item) => {
				const type = item.acceptType?.type;
				const quantity = Number(item.quantity * (item.unit?.relationship || 0)) || 0;

				if (!acc[type]) {
					acc[type] = 0;
				}

				acc[type] += quantity;
				this.readMe(acc);
				return acc;
			}, {});
		}
	},

	mounted() {
		this.getProduct();
		// 初始化验收条目
		this.initCheckEntry();
		console.log('商品',JSON.stringify(this.acceptItem) );
	},

	watch: {
		acceptItem: {
			deep: true,
			handler() {
				this.getProduct();
				this.initCheckEntry();
			}
		}
	},

	methods: {
		// 初始化验收条目
		initCheckEntry() {
			this.checkEntry = {
				unit: this.acceptItem.unit || {},
				productionDate:this.productionDate,
				productionCode:this.productionCode,
				batchNo:this.bachNo,
				quantity: 0,
				acceptType: this.acceptType[0] || { type: 'normal', title: '正常验收' }
			};
			this.selectUnitList = [this.checkEntry];
		},
         
		// 单位转换说明
		beforeUnitRead() {
			if (!this.product?.unit || !this.acceptItem.unit?.id) {
				return '';
			}
			return unitRead(this.product.unit, this.acceptItem.unit.id, this.acceptItem.quantity) || '';
		},

		// 处理验收类型统计
		readMe(obj) {
			if (!obj || typeof obj !== 'object') return;

			const reslist = [];
			const acceptTypeMap = this.acceptType.reduce((map, item) => {
				map[item.type] = item.title;
				return map;
			}, {});

			for (let type of Object.keys(obj)) {
				if (acceptTypeMap[type] && obj[type] > 0) {
					reslist.push({
						title: acceptTypeMap[type],
						count: obj[type]
					});
				}
			}

			return reslist;
		},
        
		// 验收情况说明
		checkReadMe() {
			if (!this.product?.unit || this.total <= 0) return '';
			return unitRead(this.product.unit, this.product.unit[0]?.id, this.total) || '';
		},

		// 选择单位
		selectUnit(index, e) {
			if (!this.product.unit || !this.product.unit[e.detail.value]) return;

			this.selectUnitList[index].unit = this.product.unit[e.detail.value];
			this.selecunitValue = e.detail.value;
		},
        seleData(index,$event){
	    	 this.selectUnitList[index].productionDate=$event.detail.value
		},
		// 设置当前编辑索引
		handleCurrentIndex(index) {
			this.currentIndex = index;
		},
		handlepicpopup() {
			console.log('1111');
			this.$refs.picpopup.open();
		},

		// 关闭组件
		close() {
			this.$emit('close');
		},

		// 添加验收单位行
		addUnit() {
			const newUnit = {
				
							productionDate:'',
							productionCode:'',
							batchNo:'',
							quantity: 0,
							acceptType: this.acceptType[0] || { type: 'normal', title: '正常验收' },
				unit: this.product.unit?.[0] || {}
			};
			this.selectUnitList.push(newUnit);
			
			console.log('加入后',JSON.stringify(this.selectUnitList))
			// 自动聚焦到新行
			this.currentIndex = this.selectUnitList.length - 1;
		},

		// 删除验收单位行
		delUnit(index) {
			if (this.selectUnitList.length <= 1) {
				// 至少保留一行，清空数量
				this.selectUnitList[index].quantity = 0;
				return;
			}
			if (this.selectUnitList[index].quantity === 0) {
				this.selectUnitList.splice(index, 1);
				return;
			}
			uni.showModal({
				title: '确认删除',
				content: '确定要删除本行验收信息吗？',
				success: (res) => {
					if (res.confirm) {
						this.selectUnitList.splice(index, 1);
						// 调整当前索引
						if (this.currentIndex === index) {
							this.currentIndex = Math.max(0, index - 1);
						}
					}
				}
			});
		},

		// 选择验收类型
		selectAcceptType(index, e) {
			this.acceptTypeIndex = e.detail.value;
			this.selectUnitList[index].acceptType = this.acceptType[e.detail.value];
		},

		// 获取商品信息
		async getProduct() {
			if (!this.acceptItem || !this.acceptItem.productId) {
				uni.showToast({ title: '缺少商品ID', icon: 'none' });
				return;
			}

			try {
				uni.showLoading({ title: '加载商品信息...' });
				const res = await CloudDB.getDB('product', { _id: this.acceptItem.productId });

				if (res.code && res.data && res.data.length) {
					this.product = res.data[0];
					// 处理商品图片
					if (this.product.photo && this.product.photo.length) {
						console.log('photo', this.product.photo);
						this.product.photo = await Promise.all(this.product.photo.map((item) => getImgUrl(item.fileId)));
					}
					// 初始化数量数组
					this.quantities = this.product.unit ? new Array(this.product.unit.length).fill('') : [];
				} else {
					uni.showToast({ title: '未查询到商品信息', icon: 'none' });
				}
			} catch (e) {
				console.error('获取商品信息失败：', e);
				uni.showToast({ title: '加载失败', icon: 'none' });
			} finally {
				uni.hideLoading();
			}
		},

		// 图片加载失败处理
		onImgError(index) {
			// 替换为默认图片
			if (this.product.photo && this.product.photo[index]) {
				this.product.photo[index] = '/static/images/default-product.png';
			}
		},

		// 确认验收
		async handleConfirm() {
			// 前端验证
			if (!this.acceptItem.productId) {
				return uni.showToast({ title: '商品ID不能为空', icon: 'none' });
			}

			if (!this.selectUnitList.some((item) => Number(item.quantity) > 0)) {
				return uni.showToast({ title: '请填写验收数量', icon: 'none' });
			}

			// 构建表单数据
			const form = this.buildCheckForm();
			const total = form.checkDetails.reduce((sum, item) => sum + item.convertedQuantity, 0);
			const checkForm = { ...form, totalQuantity: total };
			this.acceptanceStatus = this.checkAcceptanceStatus(checkForm);
			const submitForm = { ...checkForm, checkStatus: this.acceptanceStatus };
		
			// 调用接口提交
			try {
				uni.showLoading({ title: '提交中...' });
				const res = await CloudDB.inventoryCheck(submitForm);
                 console.log("提交的验收明细",JSON.stringify(submitForm));
				if (res.code) {
					uni.showToast({ title: '验收成功', icon: 'success' });

					this.$emit('success', { ...submitForm }); // 通知父组件验收成功
					this.close();
				} else {
					uni.showToast({ title: res.errMsg || '提交失败', icon: 'none' });
				}
			} catch (err) {
				console.error('提交失败', err);
				uni.showToast({ title: '提交失败，请重试', icon: 'none' });
			} finally {
				uni.hideLoading();
			}
		},

		// 构建提交表单(自定义验收指令未完成)
		buildCheckForm() {
		
			return {
				productId: this.acceptItem.productId,
				spec:this.acceptItem.spec,
				acceptItemId: this.acceptItem._id,
				checkDetails: this.selectUnitList
					.filter((item) => Number(item.quantity) > 0)
					.map((unit) => ({
						checkType: unit.acceptType,
						quantity: Number(unit.quantity),
						productionDate:unit.productionDate,
						productionCode:unit.productionCode,
						batchNo:unit.batchNo,
					    unitId: unit.unit.id,
						unitName: unit.unit.unitName,
						relationship: Number(unit.unit.relationship) || 0,
						convertedQuantity: Number(unit.quantity) * (Number(unit.unit.relationship) || 0)
					})),
				unitId: this.product.unit?.[0]?.id || '',
				unitName: this.product.unit?.[0]?.unitName || '',
				applyQuantity: this.acceptItem.quantity || 0,
				applyUnit: this.acceptItem.unit?.unitName || '',
				checkerId: store.userInfo?._id || '',
				checkerName: store.userInfo?.userName || store.userInfo?.nicName || '未知',
				checkTime: Date.now()
			};
		},
		checkAcceptanceStatus(form) {
			console.log('33333', JSON.stringify(this.selectUnitList));
			// 检查数量是否少于申请数量
			if (form.totalQuantity < this.acceptItem.quantity) {
				return {
					value: 'quantityLess',
					label: '数量少了'
				};
			}

			// 检查数量是否多于申请数量
			if (form.totalQuantity > this.acceptItem.quantity) {
				return {
					value: 'quantityToo',
					label: '数量多了'
				};
			}

			// 收集所有非正常验收类型
			const abnormalTypes = this.selectUnitList.filter((item) => Number(item.quantity) > 0 && item.acceptType.type !== 'normal').map((item) => item.acceptType.title);
			// 存在非正常验收类型
			if (abnormalTypes.length > 0) {
				console.log('4444444444444');
				return {
					value: 'abnormal',
					label: abnormalTypes.join(',')
				};
			}

			// 所有检查都通过
			return {
				value: 'normal',
				label: '验收无误'
			};
		}
	}
};
</script>

<style lang="scss">
@import '../../common/variables.scss';
.main {
	width: 100%;
	padding-bottom: 120rpx; /* 预留底部按钮高度 */
	background-color: $color-bg-light;

}
.photo{
	display: flex;
	width: 200rpx;
	justify-content: center;
	height: 100rpx;
	color: #f5f5f5;

	border: $border-width solid $color-border;
	border-radius: $radius-base;
	background-color: #55aaff;
	padding: 0 $gap-base;
	margin: 0 auto;
}
// 扫描区域
.scanarea {
	display: flex;
	align-items: center;
	justify-content: space-between;
	width: 100%;
	max-width: 500rpx;
	height: 60rpx;
	margin: 0 auto $gap-base;
	padding: 0 20rpx;
	border: $border-width solid $color-border;
	border-radius: $radius-base;
	background-color: $color-bg-white;

	input {
		flex: 1;
		height: 100%;
		font-size: 28rpx;
	}

	uni-icons {
		font-size: 32rpx;
		color: $color-primary;
	}
}

// 滚动区域样式
.scroll {
	height: 500rpx;
	width: 100%;
	// 确保滚动区域内容不会被底部按钮遮挡
	padding-bottom: 20rpx;
}
.info-group {
	width: 100%;
	padding: 0 $gap-base;
	margin: $gap-sm 0;
	color: $color-text;
	font-size: 28rpx;

	.info-label {
		color: $color-text-secondary;
		font-weight: 600;
		margin-right: 10rpx;
	}
}

// 品名样式
.name {
	display: flex;
	flex-wrap: wrap;
	align-items: center;
	padding-top: $gap-sm;

	.name-container {
		display: flex;
		flex-wrap: wrap;
		flex: 1;
	}

	.name_item {
		display: inline-flex;
		white-space: nowrap;
		padding: 8rpx 16rpx;
		margin: 5rpx;
		background-color: $color-bg-white;
		border-radius: $radius-base;
		border: $border-width solid $color-border;
		font-size: 28rpx;
		color: $color-text;
	}
}

// 规格样式
.spec {
	display: flex;
	align-items: center;
	margin: $gap-sm 0;

	.spec-value {
		color: $color-primary;
	}
}
.scroll-content {
	width: 100%;
}

// 商品图片容器（点击显示）
.productPic-container {
	width: 100%;
	margin: $gap-base auto;
}

.productPic-placeholder {
	width: 100%;
	padding: 20rpx 0;
	background-color: #eee;
	border-radius: $radius-base;
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 15rpx;
	cursor: pointer;
	transition: background-color 0.2s;

	&:active {
		background-color: #ddd;
	}
}

.productPic-text {
	font-size: 28rpx;
	color: $color-text-secondary;
}

// 图片弹窗样式
.productPic-wrapper {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	z-index: 999;
	display: flex;
	align-items: center;
	justify-content: center;
}

.productPic-overlay {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background-color: rgba(0, 0, 0, 0.8);
}

.productPic-modal {
	position: relative;
	width: 90%;
	max-width: 600rpx;
	z-index: 1000;
}

.productPic-close {
	position: absolute;
	top: -50rpx;
	right: 0;
	width: 40rpx;
	height: 40rpx;
	background-color: rgba(0, 0, 0, 0.5);
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
}

// 商品图片轮播
.productPic {
	width: 100%;
	height: 0;
	padding-bottom: 50%; /* 维持1:2的宽高比 */
	position: relative;
	background-color: #eee;
	margin: $gap-base auto;

	.swiper-item {
		width: 100%;
		height: 100%;
		position: absolute;
		top: 0;
		left: 0;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.product-img {
		width: 100%;
		height: auto;
		max-height: 80vh;
		object-fit: contain;
	}
}

// 无图片占位
.no-pic {
	width: 100%;
	height: 0;
	padding-bottom: 50%;
	background-color: #eee;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	color: $color-text-light;
	position: relative;

	.no-pic-text {
		margin-top: 20rpx;
		font-size: 26rpx;
	}
}

// 批次选择区
.batch_order {
	display: flex;
	flex-wrap: wrap;
	justify-content: flex-start;
	padding: 0 $gap-base;
	margin: $gap-base 0;
}

.batch_order_item {
	min-width: 120rpx;
	height: 55rpx;
	margin: 10rpx 8rpx;
	padding: 0 15rpx;
	border-radius: $radius-base;
	border: $border-width solid $color-border;
	display: flex;
	align-items: center;
	justify-content: center;
	cursor: pointer;
	transition: all 0.2s;
	font-size: 26rpx;

	&.select {
		background-color: $color-primary;
		color: $color-bg-white;
		border-color: $color-primary;
	}

	&:active {
		transform: scale(0.98);
	}
}

// 数量信息区域
.quantity {
	display: flex;
	flex-direction: column;
	align-items: flex-start;
	gap: 10rpx;
	padding: $gap-sm $gap-base;

	.quantity-item {
		display: flex;
		flex-wrap: wrap;
		align-items: center;
		width: 100%;
	}

	.check-status {
		display: flex;
		align-items: center;
		width: 100%;
		color: $color-primary;
	}

	.quantity-note {
		font-size: 24rpx;
		color: $color-text-light;
		margin-left: 10rpx;
	}
}

// 验收明细区域
.order_area {
	background-color: #dedede;
	margin: $gap-base;
	padding: $gap-base;
	border-radius: $radius-base;

	.empty-state {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 200rpx;
		color: $color-text-light;
		font-size: 28rpx;
	}
}

// 数量输入行
.quantity_0 {
	display: flex;
	align-items: center;
	gap: 20rpx;
	width: 100%;
	margin: 20rpx 0;
	padding: 0 10rpx;
}

// 底部占位元素，确保最后一行有足够间距
.bottom-spacing {
	height: $bottom-spacing;
	visibility: hidden;
}


.acceptType {
	display: flex;
	width: 160rpx;
	padding: 10rpx;
	text-align: center;
	border-radius: $radius-base;
	background-color: $color-bg-white;
	border: $border-width solid $color-border;
	color: $color-success;
}

.acceptType_err {
	color: $color-error;
}

.quantity {
	width: 80rpx;
}
.batch {
	width: 100rpx;
}
.mode_date {
    display: flex;
	justify-content: center;
	width: 180rpx;
}
.comtom{
	display: flex;
}
.input {
    display: flex;
	padding: 10rpx 12rpx;
	border-radius: $radius-base;
	border: $border-width solid $color-border;
	background-color: $color-bg-white;
	text-align: right;
}

.unitarea {
	flex: 1;
	max-width: 120rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	height: 60rpx;
	padding: 0 10rpx;
	background-color: $color-bg-white;
	border: $border-width solid $color-border;
	border-radius: $radius-base;

	input {
		flex: 1;
		text-align: center;
		background-color: transparent;
	}

	uni-icons {
		font-size: 24rpx;
		color: $color-text-light;
	}
}

.action-btn {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 50rpx;
	height: 50rpx;
	border-radius: 50%;
	transition: all 0.2s;

	&:active {
		transform: scale(0.9);
	}
}

.add {
	display: flex;
    align-items: center;
	justify-content: center;
	background-color: $color-primary;
	color: $color-bg-white;
	font-size: 36rpx;
	line-height: 40rpx;
	width: 200rpx;
	height: 60rpx;
	border-radius: 30rpx;
	margin: 0 auto;
}
.no{
	width: 60rpx;
	height: 60rpx;
	border-radius: 30rpx;
}

.del {
	background-color: transparent;
}

// 底部按钮组
.btn-group {
	position: absolute;
	bottom: 0;
	left: 0;
	width: 100%;
	height: 100rpx;
	display: flex;
	background-color: $color-bg-white;
	border-top: $border-width solid $color-border;
	z-index: 10;

	.cancel-btn,
	.confirm-btn {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
		font-weight: 500;
	}

	.cancel-btn {
		color: $color-text-secondary;
		background-color: #f5f5f5;
		border-right: $border-width solid $color-border;
	}

	.confirm-btn {
		color: $color-bg-white;
		background-color: $color-primary;
		transition: background-color 0.2s;

		&:active {
			background-color: $color-primary-dark;
		}
	}
}

// 解决picker选择器在nvue中的样式问题
::v-deep .uni-picker {
	height: 60rpx !important;
}
</style>
